CODE 79. Spiral Matrix

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/10/12/2013-10-12-CODE 79 Spiral Matrix/

访问原文「CODE 79. Spiral Matrix

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
vector<int> spiralOrder(vector<vector<int> > &matrix) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(matrix.size() == 0){
vector<int> spiralMatrix(0);
return spiralMatrix;
}
int halfCol = (matrix[0].size() - 1) / 2;
int halfRow = (matrix.size() - 1) / 2;
int col = 0;
int row = 0;
vector<int> spiralMatrix(0);
while(row <= halfRow && col <= halfCol){
for(int i = col; i < matrix[0].size() - col; i++){
spiralMatrix.push_back(matrix[row][i]);
}
for(int i = row + 1; i < matrix.size() - row; i++){
spiralMatrix.push_back(matrix[i][matrix[0].size() - col - 1]);
}
if(row != matrix.size() - row - 1){
for(int i = matrix[0].size() - col - 2; i >= col; i--){
spiralMatrix.push_back(matrix[matrix.size() - row - 1][i]);
}
}
if(col != matrix[0].size() - col){
for(int i = matrix.size() - row - 2; i >= row + 1; i--){
spiralMatrix.push_back(matrix[i][col]);
}
}
row++;
col++;
}
return spiralMatrix;
}
Jerky Lu wechat
欢迎加入微信公众号